package com.iris.live.services.report.data;

import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.repositories.impl.BaseRepository;

import java.util.*;

/**
 * @Description:数据抽取基础类
 * @author: Tony.Zhang
 * @Date: 2017-08-17 22:47
 **/
public abstract class BaseReportDataSource extends BaseRepository implements IReportDataSource {
    /**
     * 根据用户选择的品牌组合进行原始数据的合计
     *
     * @param context
     * @param datas
     * @throws Exception
     */
    protected void brandGroup(ReportContext context, List<Map> datas) throws Exception {
        if (context.getDynamicIndicatorValues() == null || context.getDynamicIndicatorValues().trim().isEmpty()) {
            return;
        }
        List<Set<String>> groupSet = new ArrayList<>(); //用户选择的品牌组合
        String[] groups = context.getDynamicIndicatorValues().split("[|]");
        for (String group : groups) {
            Set<String> set = new HashSet<>();

            String[] keys = group.split("[+]");
            for (String key : keys) {
                set.add(key);
            }

            groupSet.add(set);
        }

        Set<String> dataKeys = null, dataGroupKeys = new HashSet<>();
        String[] strDataGroupKeys = context.getDataGroupKeys().split(",");//品牌值忽略集合
        for (String strDataGroupKey : strDataGroupKeys) {
            dataGroupKeys.add(strDataGroupKey.trim());
        }

        Map<String, Map> groupValues = new HashMap<>();
        Map groupValue = null;
        StringBuffer sbKey = new StringBuffer();
        for (Map data : datas) {
            for (int index = 0; index < groupSet.size(); index++) {
                Set<String> keys = groupSet.get(index); //用户选定的分组
                if (keys.contains(data.get(context.getIndicatorGroupKey()).toString())) { //当前数据记录属于指定用户选择的分组，则需要进行统计
                    //构建新建分组数据中非统计部分数据
                    sbKey.setLength(0);
                    for (String groupKey : dataGroupKeys) { //将data中分组字段拼接成一个字符串
                        if (StringUtils.isNotNullOrBlank(data.get(groupKey.trim()))) {
                            sbKey.append(index).append("_").append(groupKey.trim()).append("_").append(data.get(groupKey.trim()).toString());
                        }
                    }

                    if (groupValues.containsKey(sbKey.toString())) {
                        groupValue = groupValues.get(sbKey.toString());
                    } else {
                        groupValue = new HashMap<>();
                    }

                    //构建新建分组数据中统计部分数据
                    dataKeys = data.keySet();
                    for (String mKey : dataKeys) {
                        if (mKey.equals(context.getIndicatorGroupKey())) { //
                            groupValue.put(mKey.trim(), groups[index]);
                        } else if (dataGroupKeys.contains(mKey.trim())) { //分组字段数据直接拷贝
                            groupValue.put(mKey, data.get(mKey));
                        } else { //分组统计字段处理
                            if (!groupValue.containsKey(mKey)) {
                                groupValue.put(mKey, 0d);
                            }

                            if (data.get(mKey) != null && !"".equals(data.get(mKey))) {
                                groupValue.put(mKey, Double.parseDouble(groupValue.get(mKey).toString()) + Double.parseDouble(data.get(mKey).toString()));
                            }
                        }
                    }

                    groupValues.put(sbKey.toString(), groupValue);
                }
            }
        }

        for (Map gv : groupValues.values()) { //将分组统计数据放入结果集中
            datas.add(gv);
        }
    }

    protected String getOrgTerms(String prefix, Map info, Map params){
        String orgTerm = "";

        if(StringUtils.isNotNullOrBlank(info.get("selRegionCode")) && !"all".equalsIgnoreCase(info.get("selRegionCode").toString())){
            orgTerm += " AND (#permit.大区= :selRegionCode  or  #permit.大区_EN=:selRegionCode)";
            params.put("selRegionCode", info.get("selRegionCode"));
        }

        String selPMACode = info.get("selPMACode").toString();
        if(StringUtils.isNotNullOrBlank(selPMACode) && !"all".equalsIgnoreCase(selPMACode)){
            orgTerm += " AND UPPER((IF(IFNULL(#permit.CTA,'')='', 'OTHER',a.CTA))=:selPMACode or  UPPER(IF(IFNULL(#permit.CTA_EN,'')='', 'OTHER', a.CTA_EN))=:selPMACode)";
            params.put("selPMACode", selPMACode.toUpperCase());
        }

        if(StringUtils.isNotNullOrBlank(info.get("selDealerCode")) && !"all".equalsIgnoreCase(info.get("selDealerCode").toString())){
            orgTerm += " AND #permit.许可_BMBS=:permit";
            params.put("permit", info.get("permit"));
        }

        if(orgTerm.equals("")){
            return "";
        }else{
            return orgTerm.replaceAll("#permit",prefix.trim()).substring(orgTerm.indexOf("AND") + 3);
        }
    }

}
